#!/usr/bin/env node
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
  CallToolRequestSchema,
  ErrorCode,
  ListResourcesRequestSchema,
  ListResourceTemplatesRequestSchema,
  ListToolsRequestSchema,
  McpError,
  ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import axios from 'axios';
import * as cheerio from 'cheerio';

// 百度贴吧帖子接口类型定义
interface TiebaPost {
  id: string;
  title: string;
  author: string;
  content: string;
  reply_count: number;
  create_time: string;
  forum_name: string;
  is_top: boolean;
  is_good: boolean;
}

interface TiebaRecommendResponse {
  posts: TiebaPost[];
  total: number;
  page: number;
  page_size: number;
  has_more?: boolean;
  last_tid?: string;
}

// 百度贴吧 API 响应接口
interface TiebaApiResponse {
  no: number;
  error: string;
  data: {
    total: number;
    has_more: number;
    html: string;
    last_tid: number;
  };
}

// 帖子回复接口
interface TiebaReply {
  floor: number;
  post_id: string;
  author: string;
  author_id: string;
  content: string;
  create_time: string;
  reply_count: number;
  is_author: boolean;
}

// 帖子详情接口
interface TiebaPostDetail {
  id: string;
  title: string;
  author: string;
  author_id: string;
  content: string;
  create_time: string;
  forum_name: string;
  forum_id: string;
  reply_count: number;
  view_count: number;
  is_top: boolean;
  is_good: boolean;
  replies: TiebaReply[];
}

// 帖子评论接口
interface TiebaComment {
  thread_id: number;
  post_id: string;
  content: string;
  username: string;
  show_nickname: string;
  now_time: number;
  user_id: number;
  comment_id: string;
  cite_name?: string;
}

interface TiebaCommentsResponse {
  errno: number;
  errmsg: string;
  data: {
    comment_list: {
      [post_id: string]: {
        comment_num: number;
        comment_list_num: number;
        comment_info: TiebaComment[];
      };
    };
    user_list: {
      [user_id: string]: {
        user_name: string;
        show_nickname: string;
        portrait: string;
      };
    };
  };
}

// 验证获取推荐帖子参数
const isValidRecommendArgs = (
  args: any
): args is {
  forum?: string;
  page?: number;
  page_size?: number;
  offset?: number;
  last_tid?: string;
} =>
  typeof args === 'object' &&
  args !== null &&
  (args.forum === undefined || typeof args.forum === 'string') &&
  (args.page === undefined || typeof args.page === 'number') &&
  (args.page_size === undefined || typeof args.page_size === 'number') &&
  (args.offset === undefined || typeof args.offset === 'number') &&
  (args.last_tid === undefined || typeof args.last_tid === 'string');


// 验证获取帖子评论参数
const isValidPostCommentsArgs = (
  args: any
): args is {
  thread_id: string;
  forum_id: string;
  page?: number;
  see_lz?: number;
} =>
  typeof args === 'object' &&
  args !== null &&
  typeof args.thread_id === 'string' &&
  typeof args.forum_id === 'string' &&
  (args.page === undefined || typeof args.page === 'number') &&
  (args.see_lz === undefined || typeof args.see_lz === 'number');

class BaiduTiebaMcpServer {
  private server: Server;
  private axiosInstance;
  private cookies: string = '';

  constructor() {
    this.server = new Server(
      {
        name: 'baidu-tieba-mcp-server',
        version: '1.0.0',
      },
      {
        capabilities: {
          resources: {},
          tools: {},
        },
      }
    );

    // 从环境变量读取 cookie
    this.cookies = process.env.TIEBA_COOKIE || '';

    // 创建axios实例，用于调用百度贴吧API
    this.axiosInstance = axios.create({
      baseURL: 'https://tieba.baidu.com',
      timeout: 10000,
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'X-Requested-With': 'XMLHttpRequest',
      },
    });

    // 如果有 cookie，添加到默认请求头中
    if (this.cookies) {
      this.axiosInstance.defaults.headers.common['Cookie'] = this.cookies;
    }

    this.setupResourceHandlers();
    this.setupToolHandlers();
    
    // 错误处理
    this.server.onerror = (error) => console.error('[MCP Error]', error);
    process.on('SIGINT', async () => {
      await this.server.close();
      process.exit(0);
    });
  }

  // 设置资源处理器
  private setupResourceHandlers() {
    // 静态资源列表
    this.server.setRequestHandler(ListResourcesRequestSchema, async () => ({
      resources: [
        {
          uri: 'tieba://hot/posts',
          name: '热门帖子列表',
          mimeType: 'application/json',
          description: '获取百度贴吧当前热门帖子列表',
        },
        {
          uri: 'tieba://recommend/posts',
          name: '推荐帖子列表',
          mimeType: 'application/json',
          description: '获取百度贴吧推荐帖子列表',
        },
      ],
    }));

    // 动态资源模板
    this.server.setRequestHandler(
      ListResourceTemplatesRequestSchema,
      async () => ({
        resourceTemplates: [
          {
            uriTemplate: 'tieba://{forum}/posts',
            name: '指定贴吧的帖子列表',
            mimeType: 'application/json',
            description: '获取指定贴吧的帖子列表',
          },
          {
            uriTemplate: 'tieba://post/{post_id}',
            name: '帖子详情',
            mimeType: 'application/json',
            description: '获取指定帖子的详细信息和回复列表',
          },
        ],
      })
    );

    // 读取资源处理器
    this.server.setRequestHandler(
      ReadResourceRequestSchema,
      async (request) => {
        const uri = request.params.uri;

        if (uri === 'tieba://hot/posts' || uri === 'tieba://recommend/posts') {
          return {
            contents: [
              {
                uri: request.params.uri,
                mimeType: 'application/json',
                text: JSON.stringify(
                  await this.getRecommendPosts(),
                  null,
                  2
                ),
              },
            ],
          };
        }

        // 处理动态资源
        const forumMatch = uri.match(/^tieba:\/\/([^/]+)\/posts$/);
        if (forumMatch) {
          const forum = decodeURIComponent(forumMatch[1]);
          return {
            contents: [
              {
                uri: request.params.uri,
                mimeType: 'application/json',
                text: JSON.stringify(
                  await this.getRecommendPosts(forum),
                  null,
                  2
                ),
              },
            ],
          };
        }


        const postMatch = uri.match(/^tieba:\/\/post\/(.+)$/);
        if (postMatch) {
          const postId = decodeURIComponent(postMatch[1]);
          return {
            contents: [
              {
                uri: request.params.uri,
                mimeType: 'application/json',
                text: JSON.stringify(
                  await this.getPostDetail(postId, 1, 0),
                  null,
                  2
                ),
              },
            ],
          };
        }

        throw new McpError(
          ErrorCode.InvalidRequest,
          `不支持的资源URI: ${uri}`
        );
      }
    );
  }

  // 设置工具处理器
  private setupToolHandlers() {
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          name: 'get_recommend_posts',
          description: '获取百度贴吧推荐帖子列表',
          inputSchema: {
            type: 'object',
            properties: {
              forum: {
                type: 'string',
                description: '贴吧名称（可选）',
              },
              page: {
                type: 'number',
                description: '页码（默认为1）',
                minimum: 1,
              },
              page_size: {
                type: 'number',
                description: '每页帖子数量（默认为20）',
                minimum: 1,
                maximum: 100,
              },
              offset: {
                type: 'number',
                description: '偏移量（默认为0）',
                minimum: 0,
              },
              last_tid: {
                type: 'string',
                description: '上一页最后一个帖子ID（用于分页）',
              },
            },
            required: [],
          },
        },
        {
          name: 'get_post_detail',
          description: '获取帖子的详细信息和回复列表',
          inputSchema: {
            type: 'object',
            properties: {
              post_id: {
                type: 'string',
                description: '帖子ID（如：9912790371）',
              },
              page: {
                type: 'number',
                description: '页码（默认为1）',
                minimum: 1,
              },
              see_lz: {
                type: 'number',
                description: '是否只看楼主（0=否，1=是，默认为0）',
                enum: [0, 1],
              },
            },
            required: ['post_id'],
          },
        },
        {
          name: 'get_post_comments',
          description: '获取帖子的评论列表',
          inputSchema: {
            type: 'object',
            properties: {
              thread_id: {
                type: 'string',
                description: '帖子ID',
              },
              forum_id: {
                type: 'string',
                description: '贴吧ID',
              },
              page: {
                type: 'number',
                description: '页码（默认为1）',
                minimum: 1,
              },
              see_lz: {
                type: 'number',
                description: '是否只看楼主（0=否，1=是，默认为0）',
                enum: [0, 1],
              },
            },
            required: ['thread_id', 'forum_id'],
          },
        },
      ],
    }));

    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args } = request.params;

      try {
        switch (name) {
          case 'get_recommend_posts':
            if (!isValidRecommendArgs(args)) {
              throw new McpError(
                ErrorCode.InvalidParams,
                '无效的推荐帖子参数'
              );
            }
            return {
              content: [
                {
                  type: 'text',
                  text: JSON.stringify(
                    await this.getRecommendPosts(
                      args.forum,
                      args.page || 1,
                      args.page_size || 20,
                      args.offset || 0,
                      args.last_tid
                    ),
                    null,
                    2
                  ),
                },
              ],
            };


          case 'get_post_detail':
            if (!args || typeof args.post_id !== 'string') {
              throw new McpError(
                ErrorCode.InvalidParams,
                '需要提供有效的帖子ID'
              );
            }
            return {
              content: [
                {
                  type: 'text',
                  text: JSON.stringify(
                    await this.getPostDetail(
                      args.post_id,
                      typeof args.page === 'number' ? args.page : 1,
                      typeof args.see_lz === 'number' ? args.see_lz : 0
                    ),
                    null,
                    2
                  ),
                },
              ],
            };

          case 'get_post_comments':
            if (!isValidPostCommentsArgs(args)) {
              throw new McpError(
                ErrorCode.InvalidParams,
                '需要提供有效的帖子ID和贴吧ID'
              );
            }
            return {
              content: [
                {
                  type: 'text',
                  text: JSON.stringify(
                    await this.getPostComments(
                      args.thread_id,
                      args.forum_id,
                      args.page || 1,
                      args.see_lz || 0
                    ),
                    null,
                    2
                  ),
                },
              ],
            };

          default:
            throw new McpError(
              ErrorCode.MethodNotFound,
              `未知的工具: ${name}`
            );
        }
      } catch (error) {
        if (error instanceof McpError) {
          throw error;
        }
        return {
          content: [
            {
              type: 'text',
              text: `执行工具时发生错误: ${error instanceof Error ? error.message : String(error)}`,
            },
          ],
          isError: true,
        };
      }
    });
  }


  // 解析HTML内容提取帖子信息
  private parsePostsFromHtml(html: string): TiebaPost[] {
    const $ = cheerio.load(html);
    const posts: TiebaPost[] = [];

    $('.j_feed_li').each((index, element) => {
      const $element = $(element);
      
      // 跳过广告位
      if ($element.hasClass('home-place-item')) {
        return;
      }

      const threadId = $element.attr('data-thread-id');
      const forumId = $element.attr('data-forum-id');
      
      if (!threadId || !forumId) {
        return;
      }

      // 提取帖子标题
      const titleElement = $element.find('.title.feed-item-link');
      const title = titleElement.attr('title') || titleElement.text().trim();

      // 提取贴吧名称
      const forumElement = $element.find('.n_name.feed-forum-link');
      const forumName = forumElement.attr('title') || forumElement.text().replace('吧', '');

      // 提取作者
      const authorElement = $element.find('.post_author');
      const author = authorElement.text().trim();

      // 提取内容预览
      const contentElement = $element.find('.n_txt');
      const content = contentElement.text().trim();

      // 提取回复数
      const replyElement = $element.find('.list-post-num em');
      const replyCount = parseInt(replyElement.attr('data-num') || '0', 10);

      // 提取时间
      const timeElement = $element.find('.time');
      const createTime = timeElement.text().trim();

      posts.push({
        id: threadId,
        title: title,
        author: author,
        content: content,
        reply_count: replyCount,
        create_time: createTime,
        forum_name: forumName,
        is_top: false, // HTML中没有明确的置顶标识
        is_good: false, // HTML中没有明确的精华标识
      });
    });

    return posts;
  }

  // 获取推荐帖子（调用真实API）
  private async getRecommendPosts(
    forum?: string,
    page: number = 1,
    pageSize: number = 20,
    offset: number = 0,
    lastTid?: string
  ): Promise<TiebaRecommendResponse> {
    try {
      // 构建请求参数
      const params: any = {
        is_new: 1,
        tag_id: 'like',
        limit: pageSize,
        offset: offset,
        _: Date.now(),
      };

      if (lastTid) {
        params.last_tid = lastTid;
      }

      // 调用百度贴吧推荐帖子API
      const response = await this.axiosInstance.get('/f/index/feedlist', {
        params,
        headers: {
          'Referer': 'https://tieba.baidu.com/',
        },
      });

      const apiResponse: TiebaApiResponse = response.data;

      if (apiResponse.no !== 0) {
        throw new Error(`API错误: ${apiResponse.error}`);
      }

      // 解析HTML内容
      const posts = this.parsePostsFromHtml(apiResponse.data.html);

      // 如果指定了贴吧，进行过滤
      let filteredPosts = posts;
      if (forum) {
        filteredPosts = posts.filter(post =>
          post.forum_name.includes(forum) || post.title.includes(forum)
        );
      }

      return {
        posts: filteredPosts,
        total: apiResponse.data.total,
        page,
        page_size: pageSize,
        has_more: apiResponse.data.has_more === 1,
        last_tid: apiResponse.data.last_tid.toString(),
      };

    } catch (error) {
      console.error('获取推荐帖子失败:', error);
      
      // 如果API调用失败，返回空结果
      return {
        posts: [],
        total: 0,
        page,
        page_size: pageSize,
        has_more: false,
        last_tid: '',
      };
    }
  }


  // 获取帖子详情和回复列表
  private async getPostDetail(
    postId: string,
    page: number = 1,
    seeLz: number = 0
  ): Promise<TiebaPostDetail> {
    try {
      // 构建帖子URL
      const url = `/p/${postId}`;
      const params: any = {
        pn: page,
      };

      if (seeLz === 1) {
        params.see_lz = 1;
      }

      // 请求帖子页面HTML
      const response = await this.axiosInstance.get(url, {
        params,
        headers: {
          'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
          'Referer': 'https://tieba.baidu.com/',
        },
      });

      const html = response.data;
      const $ = cheerio.load(html);

      // 提取帖子基本信息
      const title = $('.core_title_txt').attr('title') || $('.core_title_txt').text().trim();
      const forumName = $('.card_title_fname').text().replace('吧', '').trim();
      
      // 从页面脚本中提取forum_id和其他信息
      let forumId = '';
      let threadId = '';
      const scriptTexts = $('script').map((_, script) => $(script).html()).get().join('\n');
      
      // 提取forum_id
      const forumIdMatch = scriptTexts.match(/forum_id['"]\s*:\s*['"]*(\d+)['"]*/) ||
                          scriptTexts.match(/PageData\.forum\.forum_id\s*=\s*['"]*(\d+)['"]*/) ||
                          scriptTexts.match(/"forum_id"\s*:\s*['"]*(\d+)['"]*/);
      if (forumIdMatch) {
        forumId = forumIdMatch[1];
      }
      
      // 提取thread_id
      const threadIdMatch = scriptTexts.match(/thread_id['"]\s*:\s*['"]*(\d+)['"]*/) ||
                           scriptTexts.match(/PageData\.thread\.thread_id\s*=\s*['"]*(\d+)['"]*/) ||
                           scriptTexts.match(/"thread_id"\s*:\s*['"]*(\d+)['"]*/);
      if (threadIdMatch) {
        threadId = threadIdMatch[1];
      }

      // 提取楼主信息和内容 - 使用更精确的选择器
      const mainPost = $('.l_post.l_post_bright').first();
      let author = mainPost.find('.p_author_name').text().trim();
      let authorId = '';
      
      // 从data-field中提取作者信息
      const authorDataField = mainPost.find('.p_author_name').attr('data-field');
      if (authorDataField) {
        try {
          const authorData = JSON.parse(authorDataField);
          if (authorData.un) author = authorData.un;
          if (authorData.id) authorId = authorData.id;
        } catch (e) {
          // 如果解析失败，使用href提取
          const authorHref = mainPost.find('.p_author_name').attr('href');
          if (authorHref) {
            const idMatch = authorHref.match(/id=([^&]+)/);
            if (idMatch) authorId = idMatch[1];
          }
        }
      }
      
      // 提取楼主内容 - 使用更精确的选择器
      const contentElement = mainPost.find('.d_post_content.j_d_post_content');
      let content = '';
      
      if (contentElement.length > 0) {
        // 克隆元素以避免修改原DOM
        const clonedContent = contentElement.clone();
        
        // 处理图片 - 包括表情图片
        clonedContent.find('img').each((_, img) => {
          const $img = $(img);
          const src = $img.attr('src') || $img.attr('data-original') || $img.attr('data-tb-lazyload');
          const alt = $img.attr('alt') || '';
          const className = $img.attr('class') || '';
          
          if (className.includes('BDE_Smiley')) {
            // 表情图片，保留alt文本或用[表情]替代
            $img.replaceWith(alt || '[表情]');
          } else if (src) {
            // 普通图片
            $img.replaceWith(`[图片: ${src}]`);
          } else {
            $img.replaceWith('[图片]');
          }
        });
        
        content = clonedContent.text().trim();
      }

      // 提取时间 - 从tail-info中提取，更精确的匹配
      let createTime = '';
      const timeElements = mainPost.find('.tail-info');
      timeElements.each((_, elem) => {
        const timeText = $(elem).text().trim();
        // 匹配时间格式：2025-07-30 00:04
        const timeMatch = timeText.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2})/);
        if (timeMatch) {
          createTime = timeMatch[1];
        }
      });

      // 提取统计信息 - 更精确的选择器
      let replyCount = 0;
      let viewCount = 0;
      
      // 从回复数文本中提取
      const replyNumElement = $('.l_reply_num');
      if (replyNumElement.length > 0) {
        const replyText = replyNumElement.text();
        const replyMatch = replyText.match(/(\d+)回复贴/);
        if (replyMatch) {
          replyCount = parseInt(replyMatch[1]);
        }
      }
      
      // 尝试从脚本中提取更多信息
      const replyNumMatch = scriptTexts.match(/reply_num['"]\s*:\s*['"]*(\d+)['"]*/) ||
                           scriptTexts.match(/"reply_num"\s*:\s*(\d+)/);
      if (replyNumMatch) {
        replyCount = parseInt(replyNumMatch[1]);
      }

      // 提取回复列表 - 更精确的解析
      const replies: TiebaReply[] = [];
      $('.l_post.l_post_bright.j_l_post').each((index, element) => {
        const $post = $(element);
        
        // 跳过楼主帖（第一个帖子）
        if (index === 0) return;

        // 从data-pid属性获取帖子ID
        const postId = $post.attr('data-pid') || '';
        
        // 从data-field中提取作者信息
        let replyAuthor = '';
        let replyAuthorId = '';
        
        const authorElement = $post.find('.p_author_name.j_user_card');
        if (authorElement.length > 0) {
          replyAuthor = authorElement.text().trim();
          
          // 尝试从data-field中提取更详细的作者信息
          const authorDataField = authorElement.attr('data-field');
          if (authorDataField) {
            try {
              const authorData = JSON.parse(authorDataField);
              if (authorData.un) replyAuthor = authorData.un;
              if (authorData.id) replyAuthorId = authorData.id;
            } catch (e) {
              // 如果解析失败，使用href提取
              const authorHref = authorElement.attr('href');
              if (authorHref) {
                const idMatch = authorHref.match(/id=([^&]+)/);
                if (idMatch) replyAuthorId = idMatch[1];
              }
            }
          }
        }
        
        // 提取回复内容 - 使用更精确的选择器
        const replyContentElement = $post.find('.d_post_content.j_d_post_content');
        let replyContent = '';
        
        if (replyContentElement.length > 0) {
          // 克隆元素以避免修改原DOM
          const clonedReplyContent = replyContentElement.clone();
          
          // 处理图片和表情
          clonedReplyContent.find('img').each((_, img) => {
            const $img = $(img);
            const src = $img.attr('src') || $img.attr('data-original') || $img.attr('data-tb-lazyload');
            const alt = $img.attr('alt') || '';
            const className = $img.attr('class') || '';
            
            if (className.includes('BDE_Smiley')) {
              // 表情图片
              $img.replaceWith(alt || '[表情]');
            } else if (src) {
              // 普通图片
              $img.replaceWith(`[图片: ${src}]`);
            } else {
              $img.replaceWith('[图片]');
            }
          });
          
          replyContent = clonedReplyContent.text().trim();
        }

        // 提取楼层号和时间 - 从tail-info中提取
        let floor = index + 1;
        let replyTime = '';
        let location = '';
        
        const tailInfoElements = $post.find('.tail-info');
        tailInfoElements.each((_, elem) => {
          const tailText = $(elem).text().trim();
          
          // 提取楼层号
          const floorMatch = tailText.match(/(\d+)楼/);
          if (floorMatch) {
            floor = parseInt(floorMatch[1]);
          }
          
          // 提取时间
          const timeMatch = tailText.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2})/);
          if (timeMatch) {
            replyTime = timeMatch[1];
          }
        });
        
        // 提取IP属地信息
        const locationElement = $post.find('.post-tail-wrap span').first();
        if (locationElement.length > 0) {
          const locationText = locationElement.text().trim();
          if (locationText.startsWith('IP属地:')) {
            location = locationText.replace('IP属地:', '');
          }
        }
        
        const isAuthor = replyAuthor === author;

        // 只添加有效的回复
        if (replyContent || replyAuthor) {
          replies.push({
            floor,
            post_id: postId,
            author: replyAuthor,
            author_id: replyAuthorId,
            content: replyContent,
            create_time: replyTime,
            reply_count: 0, // 回复的评论数需要单独获取
            is_author: isAuthor,
          });
        }
      });

      return {
        id: postId,
        title,
        author,
        author_id: authorId,
        content,
        create_time: createTime,
        forum_name: forumName,
        forum_id: forumId,
        reply_count: replyCount,
        view_count: viewCount,
        is_top: false, // 需要从页面其他地方提取
        is_good: false, // 需要从页面其他地方提取
        replies,
      };

    } catch (error) {
      console.error('获取帖子详情失败:', error);
      
      // 如果获取失败，返回基本信息
      return {
        id: postId,
        title: '获取帖子详情失败',
        author: '未知',
        author_id: '',
        content: `获取帖子详情时发生错误: ${error instanceof Error ? error.message : String(error)}`,
        create_time: new Date().toISOString(),
        forum_name: '未知',
        forum_id: '',
        reply_count: 0,
        view_count: 0,
        is_top: false,
        is_good: false,
        replies: [],
      };
    }
  }

  // 获取帖子评论
  private async getPostComments(
    threadId: string,
    forumId: string,
    page: number = 1,
    seeLz: number = 0
  ): Promise<any> {
    try {
      // 构建请求参数
      const params = {
        t: Date.now(),
        tid: threadId,
        fid: forumId,
        pn: page,
        see_lz: seeLz,
      };

      // 调用百度贴吧评论API
      const response = await this.axiosInstance.get('/p/totalComment', {
        params,
        headers: {
          'Referer': `https://tieba.baidu.com/p/${threadId}`,
        },
      });

      const apiResponse: TiebaCommentsResponse = response.data;

      if (apiResponse.errno !== 0) {
        throw new Error(`API错误: ${apiResponse.errmsg}`);
      }

      // 处理评论数据，添加用户信息
      const processedComments: any = {};
      
      for (const [postId, commentData] of Object.entries(apiResponse.data.comment_list)) {
        const comments = commentData.comment_info.map(comment => {
          const userInfo = apiResponse.data.user_list[comment.user_id.toString()];
          return {
            ...comment,
            user_info: userInfo ? {
              username: userInfo.user_name,
              show_nickname: userInfo.show_nickname,
              portrait: userInfo.portrait,
            } : null,
            create_time_formatted: new Date(comment.now_time * 1000).toLocaleString('zh-CN'),
          };
        });

        processedComments[postId] = {
          comment_num: commentData.comment_num,
          comment_list_num: commentData.comment_list_num,
          comments: comments,
        };
      }

      return {
        thread_id: threadId,
        forum_id: forumId,
        page: page,
        see_lz: seeLz,
        comment_data: processedComments,
      };

    } catch (error) {
      console.error('获取帖子评论失败:', error);
      
      // 如果API调用失败，返回空结果
      return {
        thread_id: threadId,
        forum_id: forumId,
        page: page,
        see_lz: seeLz,
        comment_data: {},
        error: error instanceof Error ? error.message : '获取评论失败',
      };
    }
  }

  async run() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
    console.error('百度贴吧 MCP 服务器已启动');
  }
}

const server = new BaiduTiebaMcpServer();
server.run().catch(console.error);